<?php

defined('ACC')||exit('Access Denied');

class Mysql{

	protected static $ins=null;
	protected $host;
	protected $userName;
	protected $passWord;
	protected $db;
	protected $port;
	protected $conn=null;

	protected function __construct(){
	
	}
	
	public static function getIns(){
		if(self::$ins===null){
			self::$ins=new Mysql();
		}
		$conf=Conf::getIns();

		self::$ins->host=$conf->host;
		self::$ins->userName=$conf->userName;
		self::$ins->passWord=$conf->passWord;
		self::$ins->db=$conf->db;
		self::$ins->port=$conf->port;

		self::$ins->connect();
		self::$ins->select_db();
		self::$ins->setChar();

		return self::$ins;
	}
	
	/* 数据库连接 */
	public function connect(){
		$this->conn=@mysql_connect($this->host,$this->userName,$this->passWord,$this->port);
		if(!$this->conn){
			$error=new Exception('数据库连接不上',9);
			throw $error;
		}
	}
	
	/* 选择数据库 */
	public function select_db(){
		$sql='use '.$this->db;
		return $this->query($sql);
	}
	
	/* 设置字符集编码 */
	public function setChar(){
		$sql='set names utf8';
		return $this->query($sql);
	}
	
	/* 执行sql语句 */
	public function query($sql){
		$res=mysql_query($sql,$this->conn);
		if(!$res){
			Log::write($sql);
		}
		return $res;
	}
	
	/* 获取所有行信息 */
	public function getAll($sql){
		$res=$this->query($sql);
		if(!$res){
			return false;
		}
		$arr=array();
		while($row=mysql_fetch_assoc($res)){
			$arr[]=$row;
		}
		return $arr;
	}
	
	/* 获取一行信息 */
	public function getRow($sql){
		$res=$this->query($sql);
		if(!$res){
			return false;
		}
		return mysql_fetch_assoc($res);
	}
	
	/* 获取一个查询信息 */
	public function getOne($sql){
		$res=$this->query($sql);
		if(!$res){
			return false;
		}
		$row=mysql_fetch_row($res);
		return $row[0];
	}
	
	/* 返回一行信息 */
	public function affected_rows(){
		return mysql_affected_rows($this->conn);
	}
	
	/* 返回最后一次添加的id号 */
	public function last_id(){
		return mysql_insert_id($this->conn);
	}
	
	/* 添加或修改信息 */
	public function autoExecute($data,$table,$act='insert',$where='') {
    
        if($act == 'insert') {
            $sql = 'insert into ' . $table . ' (';
            $sql .= implode(',',(array_keys($data)));
            $sql .= ') values (\'';
            $sql .= implode("','",array_values($data));
            $sql .= "')";
        } else if($act == 'update') {
            if(!trim($where)) {
                return false;
            }
            
            $sql = 'update ' . $table . ' set ';
            foreach($data as $k=>$v) {
                $sql .= $k;
                $sql .= '=';
                $sql .= "'".$v."',";
            }
            
            $sql = substr($sql,0,-1);
            $sql .= ' where ';
            $sql .= $where;
        } else {
            return false;
        }

        return $this->query($sql);

    }

}


?>